<?php

namespace App\Repositories;

use App\Exceptions\GeneralException;
use App\Models\UserLog;
use Carbon\Carbon;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class UserLogRepository extends BaseRepository
{
    public function model()
    {
        return UserLog::class;
    }

    /**
     * 记录用户日志
     * Date: 2018/5/30
     * @author Tenny
     * @param $uid
     * @param $service_id
     * @param $name
     * @param $operation
     * @param $history
     * @param $actuality
     * @param $order_id
     * @param $ip
     * @param $type
     * @return boolean
     * @throws \App\Exceptions\GeneralException
     */
    public function myLog($uid, $service_id = null, $name = null, $operation = null, $history = null, $actuality = null, $order_id = 0, $ip = null, $type = 1)
    {
        if (is_null(json_decode($history))) {
            if ($history) {
                $history = json_encode($history, true);
            }
        }
        if (is_null(json_decode($actuality))) {
            if ($actuality) {
                $actuality = json_encode($actuality, true);
            }
        }
        try {
            DB::table('user_log')->insert([
                'uid' => $uid,
                'type' => $type,
                'service_id' => $service_id,
                'name' => $name,
                'operation' => $operation,
                'history' => $history,
                'actuality' => $actuality,
                'order_id' => $order_id,
                'ip' => $ip,
                'created_at' => Carbon::now(),
                'updated_at' => Carbon::now(),
            ]);
        } catch (QueryException $ex) {
            throw new GeneralException('未知错误', 500);
        }
        return true;
    }

    /**
     * 获取用户日志
     * Date: 2018/5/30
     * @author Tenny
     * @param $uid
     * @param $service_id
     * @param $type 0:快递员  1:用户  2:共派管理员 3:网点管理员
     * @param $order_id
     * @param $limit
     * @return
     */
    public function getLog($uid, $service_id = false, $type = false, $order_id = false, $limit = 15)
    {
        $query = DB::table('user_log');
        if ($uid !== false) {
            $query->where('uid', '=', $uid);
        }
        if ($type !== false) {
            $query->where('type', '=', $type);
        }
        if ($service_id !== false) {
            $query->where('service_id', '=', $service_id);
        }
        if ($order_id !== false) {
            $query->where('order_id', '=', $order_id);
        }
        $admin_log = $query
            ->select('*')
            ->orderBy('created_at', 'desc')
            ->paginate($limit);
        return $admin_log;
    }

    protected function serialization(array $attributes)
    {
        // TODO: Implement serialization() method.
    }
}